package com.pedro.encoder.input.gl.render.filters;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.pedro.encoder.R;
import com.pedro.encoder.utils.gl.GlUtil;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Random;

/**
 * 龙卷风滤镜
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public class TornadoFilter extends BaseFilterRender{

    private static final String TAG = "TornadoFilter";
    private final float[] squareVertexDataFilter = {
            // X, Y, Z, U, V
            -1f, -1f, 0f, 0f, 0f, //bottom left
            1f, -1f, 0f, 1f, 0f, //bottom right
            -1f, 1f, 0f, 0f, 1f, //top left
            1f, 1f, 0f, 1f, 1f, //top right
    };
    private int program = -1;
    private int aPositionHandle = -1;
    private int aTextureHandle = -1;
    private int uMVPMatrixHandle = -1;
    private int uSTMatrixHandle = -1;

    private int uTornadoCenter = -1;
    private int uTornadoRadius = -1;
    private int uTornadoStrength = -1;
    private int uTime = -1;

    private int uSamplerHandle = -1;
    //pram
    private long frameIndex=0;
    private float touchX=0.0f;
    private float touchY=0.5f;
    private  int interval=3000;//时间间隔，每多少毫秒出发一次特效，默认200ms
    private  boolean touchRandom=true;

    private long startTime=0;
    //是否水平方向移动
    private boolean left2right=false;
    private boolean right2left=true;
    //水平方向移动完成一次的时长，多少秒
    float period = 5f;
    private float mTornadoRadius=0.2f;
    private float mTornadoStrength=20f;

    private float speedX = 0.1f;
    private float speedY = 0.01f;

    boolean randomMove = true;
    float[] numbers = {0.05f, 0.1f, 0.5f, 0.7f, 1.0f, 1.1f};
    float a = 1.0f;

    public TornadoFilter(){
        squareVertex = ByteBuffer.allocateDirect(squareVertexDataFilter.length * FLOAT_SIZE_BYTES)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer();
        squareVertex.put(squareVertexDataFilter).position(0);
        Matrix.setIdentityM(MVPMatrix, 0);
        Matrix.setIdentityM(STMatrix, 0);
    }

    public static float nextFloat(final float min, final float max) {
        return min + ((max - min) * new Random().nextFloat());
    }
    @Override
    protected void initGlFilter(Context context) {
        String vertexShader = GlUtil.getStringFromRaw(context, R.raw.simple_vertex);
        String fragmentShader =GlUtil.getStringFromRaw(context, R.raw.tronado_fragment);
        program = GlUtil.createProgram(vertexShader, fragmentShader);
        aPositionHandle = GLES20.glGetAttribLocation(program, "aPosition");
        aTextureHandle = GLES20.glGetAttribLocation(program, "aTextureCoord");
        uMVPMatrixHandle = GLES20.glGetUniformLocation(program, "uMVPMatrix");
        uSTMatrixHandle = GLES20.glGetUniformLocation(program, "uSTMatrix");

        uTornadoCenter = GLES20.glGetUniformLocation(program, "u_TornadoCenter");
        uTornadoRadius = GLES20.glGetUniformLocation(program, "u_TornadoRadius");
        uTornadoStrength = GLES20.glGetUniformLocation(program, "u_TornadoStrength");
        uTime = GLES20.glGetUniformLocation(program, "u_Time");

        uSamplerHandle = GLES20.glGetUniformLocation(program, "s_TextureMap");
        startTime=SystemClock.elapsedRealtime();

    }


    @Override
    protected void drawFilter() {
        GLES20.glUseProgram(program);

        squareVertex.position(SQUARE_VERTEX_DATA_POS_OFFSET);
        GLES20.glVertexAttribPointer(aPositionHandle, 3, GLES20.GL_FLOAT, false,
                SQUARE_VERTEX_DATA_STRIDE_BYTES, squareVertex);
        GLES20.glEnableVertexAttribArray(aPositionHandle);

        squareVertex.position(SQUARE_VERTEX_DATA_UV_OFFSET);
        GLES20.glVertexAttribPointer(aTextureHandle, 2, GLES20.GL_FLOAT, false,
                SQUARE_VERTEX_DATA_STRIDE_BYTES, squareVertex);
        GLES20.glEnableVertexAttribArray(aTextureHandle);

        GLES20.glUniformMatrix4fv(uMVPMatrixHandle, 1, false, MVPMatrix, 0);
        GLES20.glUniformMatrix4fv(uSTMatrixHandle, 1, false, STMatrix, 0);

        GLES20.glActiveTexture(GLES20.GL_TEXTURE4);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, previousTexId);
        GLES20.glUniform1i(uSamplerHandle, 4);
        //

        float tornadoCenterX=0;
        float tornadoCenterY=0;

        if (randomMove) {
            if (SystemClock.elapsedRealtime() - startTime > interval){
                Random random = new Random();
                int randomIndex = random.nextInt(numbers.length);
                a = numbers[randomIndex];
                startTime = SystemClock.elapsedRealtime();
            }
        }

        float time =frameIndex*1.0f%(150 / 120f);
        GLES20.glUniform1f(uTime, time);
        // 获取当前时间
        long currentTime = System.currentTimeMillis();

        // 周期
        float normalizedTime = (currentTime % (long)(period*1000)) / 1000.0f;  // [0, period] 归一化
//        if (left2right||right2left){
//
//            // 将归一化的时间转换为中心的 x 坐标
//            if (left2right){
//                tornadoCenterX= normalizedTime / period;
//            }else{
//                tornadoCenterX = 1.0f - (normalizedTime / period);
//            }
//        }
        double angle = currentTime / 1000.0 * 2.0 * Math.PI * speedX;
        double angle2 = currentTime / 1000.0 * 2.0 * Math.PI * (speedX * a);
        // 计算正弦函数
        double sineValueX = Math.sin(angle);
        double sineValueY = Math.sin(angle2);

        Log.d(TAG, "currentTime: " + currentTime);
        Log.d(TAG, "sineValue: " + Math.sin(angle));

        tornadoCenterX = (float) (0.5f + (sineValueX * 0.5f));
        tornadoCenterY = (float) (0.5f + (sineValueY * 0.5f));

        Log.d(TAG, "normalizedTime=" + normalizedTime);
        Log.d(TAG, "tornadoCenterX=" + tornadoCenterX + " " + "tornadoCenterY=" + tornadoCenterY);
        GLES20.glUniform2f(uTornadoCenter, tornadoCenterX, tornadoCenterY);
        GLES20.glUniform1f(uTornadoRadius, mTornadoRadius);
        GLES20.glUniform1f(uTornadoStrength, mTornadoStrength);
        GLES20.glActiveTexture(GLES20.GL_TEXTURE4);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, previousTexId);

    }

    @Override
    public void release() {
        GLES20.glDeleteProgram(program);
    }

    /**
     * 强度 0-100
     * @param tornadoStrength
     */
    public void setTornadoStrength(int tornadoStrength){
        this.mTornadoStrength= tornadoStrength;
    }

    /**
     * 强度 1-100
     * @param tornadoRadius
     */
    public void setTornadoRadius(float tornadoRadius){
        this.mTornadoRadius= (float) tornadoRadius /100;
    }
    /**
     * x轴速度调节参数
     * @param speedX
     */
    public void setSpeedX(float speedX) {
        this.speedX = speedX;
    }

    public void setRandomMove(boolean randomMove) {
        this.randomMove = randomMove;
    }
}
